/*
 * @Author: Zeratul
 * @Date: 2020-08-19 17:16:24
 * @LastEditTime: 2020-08-21 16:55:12
 * @FilePath: \sz-h5-2003-react-mobile\zhangminhui\eleme-react\eleme-user\src\pages\HomePage\index.js
 */
import React, { Component } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import styles from "./home.module.scss";
import axios from "../../utils/myaxios"
import setMeal from "../../assets/images/pingzhitaocan.webp";
import vip from "../../assets/images/vip.webp";
import NotLogin from "../../assets/images/homeIsNoLogin.png";

function filter(item) {
  if (item.indexOf("满") > -1) {
    return <span className={styles.man}>减</span>;
  } else if (item.indexOf("配") > -1) {
    return <span className={styles.pei}>配</span>;
  }
}
// 首页未登录组件
class HomeNotLogin extends Component {
  Login() {
    this.props.toLogin();
  }
  render() {
    return (
      <div className={styles.NotLogin}>
        <img src={NotLogin} alt="" />
        <span>没有结果</span>
        <span>登录后查看更多商家</span>
        <button onClick={this.Login.bind(this)}>登录</button>
      </div>
    );
  }
}
// 商家列表组件
class MerchantList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      merchantList: [
        {
          shopID: 1,
          shopPhotos: "/uploads/resize_w_150.jpg",
          shopName: "躺小鲜和范小满·大碗菜(固戍店)",
          monthlySales: "4246",
          startingPrice: "20",
          deliveryFee: 0,
          deliveryTime: "42分钟",
          tip: "盖浇饭",
          distance:2.47,
          shopDiscount: "满27减10,满30减12,配送费立减4元"
        },
      ],
      newMerchantList: [
      ],
      click:false,
    };
  }
 componentDidMount(){
  //将字符串转为数组渲染
  axios.get("/user/getAllShops").then(res=>{
    if(res.code===200){
     this.setState({
       merchantList:res.results
     },()=>{
      let Arr = JSON.parse(JSON.stringify(this.state.merchantList))
      Arr.forEach(v=>{v.shopDiscount=JSON.parse(JSON.stringify(v.shopDiscount.split(',')))})
       this.setState({
        merchantList:Arr
       },()=>{
        // 商品活动列表多出两行只显示两行
        let newMerchantList1 = JSON.parse(JSON.stringify(this.state.merchantList))
        newMerchantList1.forEach(v=>{
           v.shopDiscount.splice(2)
       })
         this.setState({
           newMerchantList: newMerchantList1
         });  
       })
     })
    }
  })
 }
// 商品列表活动点击展开 再次点击折叠
 activity(type,index){
  let newMerchantList1 = JSON.parse(JSON.stringify(this.state.merchantList))
  newMerchantList1.forEach(v=>{
     v.shopDiscount.splice(2)
 })
   if(type){
     this.setState({
         newMerchantList: newMerchantList1
       }
     );
   }else{
    newMerchantList1[index] = this.state.merchantList[index]
      this.setState({
    newMerchantList:newMerchantList1
   })
   }
   this.setState({
    click:!this.state.click
  })
 }
 ToDetail(id){
   this.props.toDetail(id)
 }
  render() {
    return (
      <div>
        {this.state.newMerchantList.map((v,index) => {
          return (
            <div className={styles.merchantList} key={v.shopID} onClick={this.ToDetail.bind(this,v.shopID)}>
              <div className={styles.merchantItemLeft}>
                <img src={"http://175.24.122.212:9090/"+v.shopPhotos} alt="" />
              </div>

              <div className={styles.merchantItemRight}>
                <div>
                  <div className={styles.merchantItemName}>{v.shopName}</div>
                  <div className={styles.sales}>月售{v.monthlySales}单</div>
                  <div>
                    <div className={styles.canBuy}>
                      <div>
                        <span>{"￥" + v.startingPrice + "起送"}</span> |
                        <span>
                          {v.deliveryFee === 0
                            ? "免配送费"
                            : "配送￥" + v.deliveryFee + "元"}
                        </span>
                      </div>
                      <div>
                        <span>{v.distence}km</span> | <span>{v.deliveryTime+"分钟"}</span>
                      </div>
                    </div>
                  </div>
                  <span className={styles.tip}>{v.tag}</span>
                </div>
                <div className={styles.activity}>
                  <div>
                    {v.shopDiscount.map((item) => {
                      return (
                        <div className={styles.activityItme} key={item}>
                          {filter(item)}
                          {item}
                        </div>
                      );
                    })}
                  </div>
                  <div className={styles.activityNum} onClick={this.activity.bind(this,this.state.click,index)}>
                    { this.state.merchantList[index].shopDiscount.length + "个活动" } 
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
}

class HomePage extends Component {
  state = {
    serveList:[
      {id:1,text:"蜂鸟专送",icon:"icon-niao",on:false,flag:true},
      {id:2,text:"到店自取",icon:"icon-dianpu",on:false,flag:true},
      {id:3,text:"品牌商家",icon:"icon-shangdian",on:false,flag:true},
      {id:4,text:"新店",icon:"icon-home",on:false,flag:true},
      {id:5,text:"接受预定",icon:"icon-dianhua",on:false,flag:true},
      {id:6,text:"食无忧",icon:"icon-icon-bao",on:false,flag:true},
      {id:7,text:"开发票",icon:"icon-fapiao",on:false,flag:true},
    ],
    flxed: false,
    changeTypeList:false,
    search: true,
    inputValue: "",
    handleClick:1,
    address:"正在定位...",
    type:-1,
    typeName:"综合排序",
    clickmodalBox:false,
    isScreen:false,
    isActivitys:-1,
    isConsume:-1,
    activitysFlag:-1,
    ConsumeFlag:-1,

  };
  componentDidMount() {
    // 滚动距离超过一百搜索栏固定
    window.addEventListener("scroll", (e)=> {
        let htmlElement = e.target;
        let scrollTop = htmlElement.scrollTop;
        if(!this.state.flxed){
            if(scrollTop > 100) {
              this.setState({
                flxed: true,
              });
            } else {
              this.setState({
                flxed: false,
              });
            }
          }else if(!this.state.clickmodalBox){
            if(scrollTop > 100) {
              this.setState({
                flxed: true,
              });
            } else {
              this.setState({
                flxed: false,
              });
            }
          }
      },true);
      // 从本地储存中获取地址信息
      if(sessionStorage.getItem("address")){
        this.setState({
          address:sessionStorage.getItem("address")
        })
      }else{
       this.timeID=setTimeout(() => {
          this.setState({
            address:sessionStorage.getItem("address")
          })
        }, 2000);
      }
  }
  componentWillUnmount(){
    clearTimeout(this.timeID)
    this.setState = ()=>false;
  }
  goToLogin = () => {
    this.props.history.push("/login");
  };
  focus(e) {
      this.setState(
      {
        search: false,
        inputValue: e.currentTarget.value,
      },
      () => {
        if (this.state.inputValue === "") {
          this.setState({
            search: true,
          });
        }
      }
    );
  }
  clickInput(){
    if(!this.props.isLogin){
      this.props.history.push("/login")
    }
  }
  // 切换类型排序
  changeType(num){
    this.setState({
      handleClick:num
    })
    if(num===2){
      this.setState({
        handleClick:num,
        flxed:false,
        changeTypeList:false,
        clickmodalBox:false,
        typeToMerchan:"距离最近"
      })
    }
    if(num===3){
      this.setState({
        handleClick:num,
        flxed:false,
        changeTypeList:false,
        clickmodalBox:false,
      })
    }
    if(num===1){
      this.setState({
        flxed:true,
        changeTypeList:true,
        clickmodalBox:true,
        isScreen:false
      })
    }
    if(num===4){
      this.setState({
        flxed:true,
        changeTypeList:true,
        clickmodalBox:true,
        isScreen:true
      })
    }
  }
  clickList(index,e){
    // 阻止事件冒泡
    e.stopPropagation()
    this.setState({
      type:index,
      flxed:false,
      changeTypeList:false,
      typeName:this.props.changeTypeArr[index].text,
      clickmodalBox:false
    })
  }
  // 商家服务
  selectServe(ind,e){
    let arr = JSON.parse(JSON.stringify(this.state.serveList))
    if(arr[ind].flag){
      arr[ind].on=true
      arr[ind].flag=!arr[ind].flag
      e.stopPropagation()
      this.setState({
        serveList:arr
      })
    }else{
      arr[ind].flag=!arr[ind].flag
      arr[ind].on=false
      e.stopPropagation()
      this.setState({
        serveList:arr
      })
    }
  }
  // 优惠活动
  selectActivitys(ind,e){
    e.stopPropagation()
    if(this.state.activitysFlag===ind){
      this.setState({
        isActivitys:-1,
        activitysFlag:-1
      })
    }else{
      this.setState({
        isActivitys:ind,
        activitysFlag:ind
      })
    }
       
  }
  // 人均消费
  selectConsume(ind,e){
    e.stopPropagation()
    if(this.state.ConsumeFlag===ind){
      this.setState({
        isConsume:-1,
        ConsumeFlag:-1
      })
    }else{
      this.setState({
        isConsume:ind,
        ConsumeFlag:ind
      })
    }
  }
// 筛选清空
  empty(e){
    e.stopPropagation()
    let newArr = JSON.parse(JSON.stringify(this.state.serveList))
    newArr.forEach(v=>{
      v.on=false
    })
    this.setState({
      serveList:newArr,
      isActivitys:-1,
      isConsume:-1,
      isScreen:-1
    })
  }
// 筛选确认
  ensure(){
    this.setState({
      clickmodalBox:false,
      flxed:false,
      changeTypeList:false
    })
  }
  goToDetail=(id)=>{
    this.props.history.push("/foodStore/order/"+id)
  }
  render() {
    return (
      <div>
        {/* 头部地址栏开始 */}
        <header>
          <div className={styles.homeAddress} style={{marginBottom:this.state.flxed?"50px":0}}>
            <svg
              className="icon"
              aria-hidden="true"
              style={{ width: "18px", height: "18px" }}
            >
              <use href="#icon-dingwei"></use>
            </svg>
            <span>{this.state.address}</span>
          </div>
        </header>
        {/* 头部地址栏结束 */}
        {/* 头部搜素框开始 */}
        <div className={this.state.flxed ? styles.searchFixedBox : styles.searchBox}>
          <div className={styles.iconBox}>
            <svg
              className="icon"
              aria-hidden="true"
              style={{
                width: "16px",
                height: "16px",
                display: this.state.search ? "block" : "none",
              }}
            >
              <use href="#icon-fangdajing1"></use>
            </svg>
          </div>
          <input
            type="text"
            placeholder="搜索吃了么商家、商品名称"
            onChange={this.focus.bind(this)}
            defaultValue={this.state.inputValue}
            onClick={this.clickInput.bind(this)}
          />
        </div>
        {/* 头部搜素框结束 */}
        {/* 导航栏开始 */}
        <div className={styles.navList}>
          {this.props.navList.map((v) => {
            return (
              <div key={v.id} className={styles.navListItem}>
                <div className={styles.itemImg}>
                  <img src={v.src} alt="" />
                </div>
                <span>{v.text}</span>
              </div>
            );
          })}
        </div>
        {/* 导航栏结束 */}
        {/* 品质套餐开始 */}
        <div style={{width:"100%",background:"#FFFFFF",padding:"10px 10px 0 10px"}}>
          <div className={styles.setMeal}>
            <div>
              <div className={styles.setMealName}>品质套餐</div>
              <div className={styles.setMealTip}>搭配齐全吃的好</div>
              <div className={styles.setMealGoBuy}>{"立即抢购  >"}</div>
            </div>
            <div className={styles.setMealImg}>
              <img src={setMeal} alt=""></img>
            </div>
          </div>
        </div>
        {/* 品质套餐结束 */}
        {/* 超级会员开始 */}
        <div style={{ width: "100%", background: "white", padding: "10px 0" }}>
          <div className={styles.superVip}>
            <div className={styles.VipBox}>
              <img src={vip} alt=""></img>
              <span>超级会员</span>
              <span>·每月领20元红包</span>
            </div>
            <span>限时6元开通 {">"}</span>
          </div>
        </div>
        {/* 超级会员结束 */}
        {/* 商家筛选开始 */}
        <div className={styles.merchant}>
          <div className={styles.recommend}>— 推荐商家 —</div>
          <div className={this.state.changeTypeList?styles.FixedMerchantType :styles.merchantType}>
            <div className={this.state.handleClick===1?styles.click:""} onClick={this.changeType.bind(this,1)}>
              {this.state.typeName}
              <svg
                className="icon"
                aria-hidden="true"
                style={{ width: "16px", height: "16px" }}
              >
                <use href="#icon-xiajiantou"></use>
              </svg>
            </div>
            <div className={this.state.handleClick===2?styles.click:""} onClick={this.changeType.bind(this,2)}>距离最近</div>
            <div className={this.state.handleClick===3?styles.click:""} onClick={this.changeType.bind(this,3)}>销量最高</div>
            <div className={this.state.handleClick===4?styles.click:""} onClick={this.changeType.bind(this,4)}>
              筛选
              <svg
                className="icon"
                aria-hidden="true"
                style={{ width: "14px", height: "14px" }}
              >
                <use href="#icon-shaixuan"></use>
              </svg>
            </div>
          </div>
        </div>
        {/* 商家筛选结束 */}
        {/* 商家列表开始 */}
        {this.props.isLogin ? (
          <MerchantList toDetail={this.goToDetail}></MerchantList>
        ) : (
          <HomeNotLogin toLogin={this.goToLogin}></HomeNotLogin>
        )}
        {/* 商家列表结束 */}
        {/* 模态框开始 */}
        <div className={this.state.clickmodalBox?styles.modalBox:styles.clickmodalBox} onClick={this.ensure.bind(this)}>
          {/* 类型列表 */}
          <div className={styles.changeTypeList} style={{display:this.state.isScreen?"none":"block"}}>
            {
              this.props.changeTypeArr.map((v,index)=>{
                return <div key={v.id} onClick={this.clickList.bind(this,index)} className={this.state.type===index?styles.on:""}>
                 <span>{v.text}</span>
                  <span style={{display:this.state.type===index?"block":"none"}}>
                    <svg
                          className="icon"
                          aria-hidden="true"
                          style={{ width: "18px", height: "18px" }}
                        >
                          <use href={"#icon-duigou"}></use>
                        </svg>
                  </span>
                </div>
              })
            }
          </div>
          {/* 筛选框 */}
          <div className={styles.screenList} style={{display:this.state.isScreen?"block":"none"}}>
            {/* 商家服务 */}
            <div className={styles.serve}>
              <span className={styles.serveTitle}>
                商家服务(可多选)
              </span>
              <div className={styles.serveList}>
                {
                  this.state.serveList.map((v,ind)=>{
                    return <div key={v.id} className={v.on?styles.onServe:""} onClick={this.selectServe.bind(this,ind)}>
                      <svg
                        className="icon"
                        aria-hidden="true"
                        style={{ width: "16px", height: "16px" }}
                      >
                        <use href={"#"+v.icon}></use>
                      </svg>
                      <span style={{marginLeft:"5px"}}>{v.text}</span>
                    </div>
                  })
                }
              </div>
            </div>
            {/* 优惠活动 */}
            <div className={styles.activitys}>
              <span className={styles.activitysTitle}>
                优惠活动(单选)
              </span>
              <div className={styles.activitysList}>
                {
                  this.props.activitysList.map((v,idx)=>{
                    return <div key={v.id} className={this.state.isActivitys===idx?styles.onServe:""} onClick={this.selectActivitys.bind(this,idx)}>
                      {v.text}
                    </div>
                  })
                }
              </div>
            </div>
            {/* 人均消费 */}
            <div className={styles.consume}>
              <span className={styles.consumeTitle}>
                人均消费
              </span>
              <div className={styles.consumeList}>
                {
                  this.props.consume.map((v,d)=>{
                    return <div key={v.id} className={this.state.isConsume===d?styles.onServe:""} onClick={this.selectConsume.bind(this,d)}>
                      {v.text}
                    </div>
                  })
                }
              </div>
            </div>
            {/* 人均消费结束 */}
            {/* 底部按钮 */}
            <div className={styles.screenBtn}>
              <div onClick={this.empty.bind(this)}>清空</div>
              <div onClick={this.ensure.bind(this)}>确定</div>
            </div>
            <div></div>
          </div>
        </div>
        {/* 模态框结束 */}
      </div>
    );
  }
}
const mapStateToProps = (state) => {
  return {
    isLogin: state.loginReducer.isLogin,
    // isLogin:true,
    serveList:state.HomeReducer.homePagesState.serveList,
    navList:state.HomeReducer.homePagesState.navList,
    changeTypeArr:state.HomeReducer.homePagesState.changeTypeArr,
    activitysList:state.HomeReducer.homePagesState.activitysList,
    consume:state.HomeReducer.homePagesState.consume
  };
};

export default connect(mapStateToProps)(withRouter(HomePage));
